package com.ly.route;

import com.ly.ConnectionUtil;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Producer {
    //交换机名称
    static final String DIRECT_EXCHANGE = "direct_exchange";
    //队列名称
    static final String DIRECT_QUEUE_INSERT = "direct_queue_insert";
    //队列名称
    static final String DIRECT_QUEUE_UPDATE = "direct_queue_update";

    public static void main(String[] args) {
        Connection connection = ConnectionUtil.getConnection();
        Channel channel = null;
        try {
            channel = connection.createChannel();
            /***
             * 声明交换机
             * 参数1：交换机名称
             * 参数2：交换机类型，fanout、topic、direct、headers
             * Fanout：广播，将消息交给所有绑定到交换机的队列
             * Direct：定向，把消息交给符合指定routing key 的队列
             * Topic：通配符，把消息交给符合routing pattern（路由模式） 的队列
             * */
            //声明交换机
            channel.exchangeDeclare(DIRECT_EXCHANGE, BuiltinExchangeType.DIRECT);
            //声明队列
            channel.queueDeclare(DIRECT_QUEUE_INSERT, false, false, false, null);
            channel.queueDeclare(DIRECT_QUEUE_UPDATE, false, false, false, null);
            //队列绑定交换机
            channel.queueBind(DIRECT_QUEUE_INSERT, DIRECT_EXCHANGE, "insert");
            channel.queueBind(DIRECT_QUEUE_UPDATE, DIRECT_EXCHANGE, "update");

            // 发送信息
            String message = "新增了商品。路由模式；routing key 为 insert ";
            channel.basicPublish(DIRECT_EXCHANGE, "insert", null, message.getBytes());
            // 发送信息
            message = "修改了商品。路由模式；routing key 为 update";
            channel.basicPublish(DIRECT_EXCHANGE, "update", null, message.getBytes());
            System.out.println("发送消息成功！");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (channel != null) {
                    channel.close();
                }
                if (connection != null) {
                    connection.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (TimeoutException e) {
                e.printStackTrace();
            }
        }
    }
}
